import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // console.log(config, '请求拦截器')
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  async response => {
    console.log(response, '响应拦截器')

    if (response.data.success) {
      console.log('响应成功')
      return response.data
    } else {
      return response.data
    }
  },
  async error => {
    console.dir(error)
    if (error.response.status === 401) {
      // console.log(success, 'success')
      console.log('响应失败')

      Message.error(error.response.data.msg)
      await store.dispatch('user/logout')
      router.push('/login')

      return Promise.reject(new Error(error))
    }
    return Promise.reject(error)
  }
)

export default service
